<script setup lang="ts">
import qs from 'qs'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './Detail'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/freetrialapply'
import { GetOptionData as GetUserOptionData } from '@/api/modules/subscriber.ts'
import { GetOptionData } from '@/api/modules/freetrial.ts'
import detailStore from '@/store/modules/cacheData'

const route = useRoute()
const router = useRouter()
const detailData = detailStore()
const imgDomain = 'https://img1.eprhan.cc'
const id = route.query.id as string

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  trialApplyId: 0,
  trialProductId: 0,
  userId: 0,
  openId: '',
  nickName: '',
  avatar: '',
  scoreOverall: 0,
  scoreItem1: 0,
  scoreItem2: 0,
  scoreItem3: 0,
  scoreItem4: 0,
  scoreItem5: 0,
  contents: '',
  pictures: [],
  viewCon: 0,
  praiseCon: 0,
  addTime: '',
  auditStatus: 0,
})

// 选择器选项Json
const OptionJson = reactive({
  userIdOption: [],
  productIdOption: [],
})

const rules = reactive({
  trialProductId: [
    { required: true, message: '请选择试用商品', trigger: 'blur' },
  ],
  // nickName: [
  //   { required: true, message: '请输入昵称', trigger: 'blur' },
  // ],
  // avatar: [
  //   { required: true, message: '请上传头像', trigger: 'blur' },
  // ],
  scoreOverall: [
    { required: true, message: '请输入推荐指数', trigger: 'blur' },
  ],
  scoreItem1: [
    { required: true, message: '请输入肤感评分', trigger: 'blur' },
  ],
  scoreItem2: [
    { required: true, message: '请输入吸收评分', trigger: 'blur' },
  ],
  scoreItem3: [
    { required: true, message: '请输入保湿评分', trigger: 'blur' },
  ],
  scoreItem4: [
    { required: true, message: '请输入滋润评分', trigger: 'blur' },
  ],
  scoreItem5: [
    { required: true, message: '请输入香气评分', trigger: 'blur' },
  ],
  contents: [
    { required: true, message: '请输入测评文本内容', trigger: 'blur' },
  ],
  pictures: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
  viewCon: [
    { required: true, message: '请输入浏览数量', trigger: 'blur' },
  ],
  praiseCon: [
    { required: true, message: '请输入点赞数量', trigger: 'blur' },
  ],
  addTime: [
    { required: true, message: '请选择发布时间', trigger: 'blur' },
  ],
  auditStatus: [
    { required: true, message: '请选择审核状态', trigger: 'blur' },
  ],
})

function SetUserData(id: any) {
  ruleForm.value.userId = id
  ruleForm.value.openId = (OptionJson.userIdOption as any).find((item: any) => item.userId === id)?.scOpenId
}
// 上传图片
function handleUploadSuccess(urls: string) {
  if (urls) {
    ruleForm.value.avatar = urls
  }
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      if (!params.avatar.includes('http')) {
        params.avatar = imgDomain + params.avatar
      }
      else {
        params.avatar.replace(new RegExp(imgDomain, 'g'), imgDomain)
      }
      params.pictures = (params.pictures as string[]).map((item: any) => {
        // 如果item不包含http
        if (!item.includes('http')) {
          return imgDomain + item
        }
        else {
          return item.replace(new RegExp(imgDomain, 'g'), imgDomain)
        }
      })

      params.pictures = (params.pictures as string[]).join(',')
      let totalScore = 0
      for (let i = 1; i <= 5; i++) {
        // eslint-disable-next-line ts/ban-ts-comment
        // @ts-expect-error
        totalScore += Number(params[`scoreItem${i}`])
      }
      params.scoreOverall = Math.floor(totalScore / 5)
      // console.log(params)
      if (id) {
        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            detailData.RememberFreetrialEvaluation(params)
            router.push({ name: 'freetrialevaluation' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyFreetrialEvaluation()
            router.push({ name: 'freetrialevaluation' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberFreetrialEvaluation(newValue)
  }
}, { deep: true })

onMounted(async () => {
  const params = qs.stringify({ UserIdList: [1506, 82, 60, 58, 57, 42, 33, 29, 23, 12, 11, 10, 9, 8, 7, 6, 5, 4, 1], PageIndex: 1, PageSize: 20 })
  await GetUserOptionData(params).then((res: any) => {
    OptionJson.userIdOption = res.data.items
  })
  await GetOptionData().then((res: any) => {
    OptionJson.productIdOption = res.data
  })
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.pictures = res.data.pictures.split(',')
        ruleForm.value.pictures = (ruleForm.value.pictures as string[]).map((item: any) => {
          if (item.startsWith(imgDomain)) {
            return item.replace(imgDomain, '')
          }
          else {
            return item
          }
        })
        if (!ruleForm.value.avatar.includes('http')) {
          ruleForm.value.avatar = imgDomain + ruleForm.value.avatar
        }
        // console.log(ruleForm.value)

        // ruleForm.value.avatar = ruleForm.value.avatar.replace(imgDomain, '')
      }
    })
  }
  else {
    ruleForm.value = detailData.GetFreetrialEvaluation()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="用户信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="用户ID" prop="userData">
              <el-select v-model="ruleForm.userId" placeholder="请选择用户" style="width: 240px;" @change="(value: any) => SetUserData(value)">
                <el-option
                  v-for="item in (OptionJson.userIdOption as any)"
                  :key="item.userId"
                  :label="`${item.userId}-${item.userNickName}`"
                  :value="item.userId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="昵称">
              <el-input v-model="ruleForm.nickName" style="max-width: 300px;" placeholder="请输入昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="头像">
              <ImageUpload :identification="false" :ext="['jpg', 'png']" :size="5" :max="1" :url="ruleForm.avatar" @on-success="(url) => handleUploadSuccess(url)" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="绑定试用商品ID" prop="trialProductId">
              <el-select v-model="ruleForm.trialProductId" placeholder="请选择">
                <el-option
                  v-for="item in (OptionJson.productIdOption as any)"
                  :key="item.id"
                  :label="`${item.title}`"
                  :value="item.id"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="发布时间" prop="addTime">
              <el-date-picker
                v-model="ruleForm.addTime"
                type="datetime"
                placeholder="请选择发布时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="审核状态" prop="auditStatus">
              <el-radio-group v-model="ruleForm.auditStatus">
                <el-radio :value="0">
                  待审核
                </el-radio>
                <el-radio :value="1">
                  审核成功
                </el-radio>
                <el-radio :value="2">
                  审核失败
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="推荐指数" prop="scoreOverall">
              <el-input v-model="ruleForm.scoreOverall" placeholder="请输入推荐指数分" type="number" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="肤感评分" prop="scoreItem1">
              <el-input v-model="ruleForm.scoreItem1" placeholder="请输入肤感评分" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="吸收评分" prop="scoreItem2">
              <el-input v-model="ruleForm.scoreItem2" placeholder="请输入吸收评分" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="保湿评分" prop="scoreItem3">
              <el-input v-model="ruleForm.scoreItem3" placeholder="请输入保湿评分" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="滋润评分" prop="scoreItem4">
              <el-input v-model="ruleForm.scoreItem4" placeholder="请输入滋润评分" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="香气评分" prop="scoreItem5">
              <el-input v-model="ruleForm.scoreItem5" placeholder="请输入香气评分" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="浏览数量" prop="viewCon">
              <el-input v-model="ruleForm.viewCon" placeholder="请输入浏览数量" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="点赞数量" prop="praiseCon">
              <el-input v-model="ruleForm.praiseCon" placeholder="请输入点赞数量" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="评测文本内容" prop="contents">
              <el-input v-model="ruleForm.contents" style="max-width: 900px;" :rows="5" placeholder="请输入评测文本内容" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="评测图片" prop="pictures">
              <ImagesUpload
                :identification="false"
                :height="200" :width="150" :size="5" :url="(ruleForm.pictures as string[])" :max="9" :ext="['jpg', 'png']"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 10px;
}

.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;
  }
}
</style>
